package moni.anyou.com.view.tim;

import android.Manifest;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.fragment.app.FragmentActivity;

import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.qcloud.presentation.business.InitBusiness;
import com.tencent.qcloud.presentation.business.LoginBusiness;
import com.tencent.qcloud.presentation.event.FriendshipEvent;
import com.tencent.qcloud.presentation.event.GroupEvent;
import com.tencent.qcloud.presentation.event.MessageEvent;
import com.tencent.qcloud.presentation.event.RefreshEvent;
import com.tencent.qcloud.presentation.presenter.SplashPresenter;
import com.tencent.qcloud.presentation.viewfeatures.SplashView;
import com.tencent.qcloud.sdk.Constant;
import com.tencent.qcloud.timchat.model.UserInfo;
import com.tencent.qcloud.timchat.ui.customview.DialogActivity;
import com.tencent.qcloud.tlslibrary.service.TLSService;
import com.tencent.qcloud.tlslibrary.service.TlsBusiness;
import com.tencent.qcloud.ui.NotifyDialog;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.ArrayList;
import java.util.List;

import moni.anyou.com.view.MainActivity;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.view.IndexActivity;
import moni.anyou.com.view.view.LogOut;
import moni.anyou.com.view.view.SplashActivity;
import moni.anyou.com.view.view.StartActivity;
import moni.anyou.com.view.view.account.LoginActivity;

public class TimSplashStart implements SplashView {


    SplashPresenter presenter;
    private int LOGIN_RESULT_CODE = 100;
    private int GOOGLE_PLAY_RESULT_CODE = 200;
    private final int REQUEST_PHONE_PERMISSIONS = 0;
    private static final String TAG = "mytim";
    //public static boolean isIMLogin=false;

    /**登录页*/
    private Class loginActivity=LoginActivity.class;
    /**主页*/
    private Class mainActivity=IndexActivity.class;

    public TimSplashStart(FragmentActivity activity) {
        this.activity = activity;
    }

    FragmentActivity activity;
    public void onCreate(FragmentActivity activity){
        this.activity=activity;
        final List<String> permissionsList = new ArrayList<>();
//        if (ConnectionResult.SUCCESS != GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this)){
//            Toast.makeText(this, getString(R.string.google_service_not_available), Toast.LENGTH_SHORT).show();
//            GoogleApiAvailability.getInstance().getErrorDialog(this, GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this),
//                    GOOGLE_PLAY_RESULT_CODE).show();
//        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if ((activity.checkSelfPermission(Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED)) permissionsList.add(Manifest.permission.READ_PHONE_STATE);
            if ((activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED)) permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permissionsList.size() == 0){
//                start();
            }else{
                activity.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_PHONE_PERMISSIONS);
            }
        }else{
//            start();
        }
    }



    public void start(){
        if(SysConfig.isLogin())
        {
        try {
            SharedPreferences pref = activity.getSharedPreferences("data", activity.MODE_PRIVATE);
            int loglvl = pref.getInt("loglvl", TIMLogLevel.DEBUG.ordinal());
            //初始化IMSDK
            InitBusiness.start(activity.getApplicationContext(),loglvl);
            //初始化TLS
            TlsBusiness.init(activity.getApplicationContext());


            Log.d(TAG,"islogin:"+SysConfig.isLogin());
            if(SysConfig.isLogin()) {
                UserInfo.getInstance().setId(SysConfig.uid);
                UserInfo.getInstance().setUserSig(SysConfig.userSig);
                presenter = new SplashPresenter(this);
                presenter.start();
            }else {
//                Intent intent=new Intent(activity,loginActivity);
//                activity.startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }}else
        {
//            Intent intent=new Intent(activity,loginActivity);
//            activity.startActivity(intent);
        }
    }

    @Override
    public void navToHome() {
        Log.d(TAG,"navToHome");
        Intent intent=new Intent(activity,mainActivity);
//        intent.putExtra("identify","Team_16");
//        intent.putExtra("type", TIMConversationType.Group);
//        activity.startActivity(intent);
        imLogin();

    }

    @Override
    public void navToLogin() {
//        Log.d(TAG,"navToLogin");
//        Intent intent=new Intent(activity,loginActivity);
////        intent.putExtra("identify","Team_16");
////        intent.putExtra("type", TIMConversationType.Group);
//        activity.startActivity(intent);

        Log.d(TAG,"navToLogin"+UserInfo.getInstance().getId()+" "+UserInfo.getInstance().getUserSig());

        LoginBusiness.loginIm(UserInfo.getInstance().getId(), UserInfo.getInstance().getUserSig(), new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                SysConfig.isIMLogin = false;

            }

            @Override
            public void onSuccess() {
                System.out.println("loginIm onSuccess=======================");
                Log.d(TAG,"loginIm onSuccess");
                initChat();
//                Intent intent=new Intent(activity,mainActivity);
////                intent.putExtra("identify","Team_16");
////                intent.putExtra("type", TIMConversationType.Group);
//                activity.startActivity(intent);
//                activity.finish();

            }
        });
    }

    public void goToLogin() {
//        Log.d(TAG,"navToLogin");
//        Intent intent=new Intent(activity,loginActivity);
////        intent.putExtra("identify","Team_16");
////        intent.putExtra("type", TIMConversationType.Group);
//        activity.startActivity(intent);

        initChat();
//        Intent intent=new Intent(activity,loginActivity);
//        activity.startActivity(intent);
//        activity.finish();
    }

//    /**
//     * 是否已有用户登录
//     */
//    @Override
//    public boolean isUserLoginAndfinish() {
//
//        activity.finish();
//        if(SysConfig.isLogin()) {
//            UserInfo.getInstance().setId(SysConfig.uid);
//            UserInfo.getInstance().setUserSig(SysConfig.userSig);
//            boolean isLogin = UserInfo.getInstance().getId() != null && UserInfo.getInstance().getUserSig() != null;
//
//            return isLogin;
//        }
//
//        return false;
//    }
//


    /**
     * 是否已有用户登录
     */
    @Override
    public boolean isUserLogin() {

        activity.finish();
        if(SysConfig.isLogin()) {
//            UserInfo.getInstance().setId(SysConfig.uid);
//            UserInfo.getInstance().setUserSig(SysConfig.userSig);
//            boolean isLogin = UserInfo.getInstance().getId() != null && UserInfo.getInstance().getUserSig() != null;

            Log.d("mytim","isUserLogin:"+true);
            return true;
        }
        Log.d("mytim","isUserLogin:"+false);
        return false;
    }






    public void imLogin(){
        if (!SysConfig.isIMLogin) {
            System.out.println("uid==============="+SysConfig.uid);
            UserInfo.getInstance().setId(SysConfig.uid);
            UserInfo.getInstance().setUserSig(SysConfig.userSig);
            System.out.println("userSig==============="+SysConfig.userSig);
            LoginBusiness.loginIm(UserInfo.getInstance().getId(), UserInfo.getInstance().getUserSig(), new TIMCallBack() {
                @Override
                public void onError(int i, String s) {
                    System.out.println("*onerror===========================:" + i + "  " + s);
                }

                @Override
                public void onSuccess() {
                    initChat();
                    SysConfig.isIMLogin = true;
//                Intent intent=new Intent(activity,StartActivity.class);
//                intent.putExtra("identify","Team_16");
//                intent.putExtra("type", TIMConversationType.Group);
//                activity.startActivity(intent);

                }
            });
        }
    }



    private void initChat() {
        Log.d("mytim", "initChat");
        TIMUserConfig userConfig = new TIMUserConfig();
        userConfig.setUserStatusListener(new TIMUserStatusListener() {
            @Override
            public void onForceOffline() {
                Log.d(TAG, "receive force offline message");

                //但被其他人登录  退出时强制退到登录界面
                Intent intent = new Intent(activity, LoginActivity.class);
                activity.startActivity(intent);


                //12313213 abcd 测试注释
                //AAA
            }

            @Override
            public void onUserSigExpired() {
                //票据过期，需要重新登录
                new NotifyDialog().show(activity.getString(com.tencent.qcloud.timchat.R.string.tls_expire), activity.getSupportFragmentManager(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //                            logout();
                    }
                });
            }
        })
                .setConnectionListener(new TIMConnListener() {
                    @Override
                    public void onConnected() {
                        Log.i(TAG, "onConnected");
                    }

                    @Override
                    public void onDisconnected(int code, String desc) {
                        Log.i(TAG, "onDisconnected");
                    }

                    @Override
                    public void onWifiNeedAuth(String name) {
                        Log.i(TAG, "onWifiNeedAuth");
                    }
                });

        //设置刷新监听
        RefreshEvent.getInstance().init(userConfig);
        userConfig = FriendshipEvent.getInstance().init(userConfig);
        userConfig = GroupEvent.getInstance().init(userConfig);
        userConfig = MessageEvent.getInstance().init(userConfig);
        TIMManager.getInstance().setUserConfig(userConfig);
    }


    /**
     * 判断小米推送是否已经初始化
     */
    private boolean shouldMiInit() {
        ActivityManager am = ((ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = activity.getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 清楚所有通知栏通知
     */
    private void clearNotification(){
        NotificationManager notificationManager = (NotificationManager) activity
                .getSystemService(activity.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        MiPushClient.clearNotification(activity.getApplicationContext());
    }


    //注释3 wo de daima tijiao
}
